package com.android.bind.components;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import com.android.bind.annotation.BindLayout;
import com.android.bind.annotation.BindView;
import android.app.Activity;

public class ActivityBind {
	private final static String SET_CONTENT_VIEW = "setContentView";
	private final static String FIND_VIEW_BY_ID = "findViewById";

	public static void bind(Activity activity) {
		if (activity == null) {
			return;
		}
		bindLayout(activity);
		bindViews(activity);
		bindEvents(activity);
	}

	private static void bindLayout(Activity activity) {
		Class<? extends Activity> clazz = activity.getClass();
		BindLayout layout = (BindLayout) clazz.getAnnotation(BindLayout.class);
		if (layout != null) {
			int layoutId = layout.value();
			try {
				Method method = clazz.getMethod(SET_CONTENT_VIEW, int.class);
				method.setAccessible(true);
				if (method != null) {
					method.invoke(activity, layoutId);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

	private static void bindViews(Activity activity) {
		Class<? extends Activity> clazz = activity.getClass();
		Field[] fields = clazz.getDeclaredFields();
		if (fields != null && fields.length > 0) {
			for (Field field : fields) {
				field.setAccessible(true);
				BindView viewInject = field.getAnnotation(BindView.class);
				if (viewInject != null) {
					int viewId = viewInject.value();
					if (viewId > 0) {
						try {
							Method method = clazz.getMethod(FIND_VIEW_BY_ID,
									int.class);
							method.setAccessible(true);
							Object obj = method.invoke(activity, viewId);
							field.set(activity, obj);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
	}

	private static void bindEvents(Activity activity) {
		EventManager.bindEvents(activity);
	}

}
